//! 事件驱动系统示例
//! 
//! 演示如何使用事件驱动模块处理Redis命令事件

use redis_rs2::event::{
    Event, EventDispatcher, DispatcherConfig, StringPayload, 
    DynamicEventHandler, EventResult, Priority, EventMetadata
};
use std::sync::Arc;
use std::thread;
use std::time::Duration;

/// 示例：Redis命令处理器
struct RedisCommandHandler {
    name: String,
}

impl RedisCommandHandler {
    fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
        }
    }
}

impl DynamicEventHandler for RedisCommandHandler {
    fn handle_dynamic(&self, event: &redis_rs2::event::DynamicEvent) -> EventResult {
        println!(
            "[{}] Processing event: {} (priority: {}, id: {})", 
            self.name, 
            event.event_type(),
            event.priority(),
            event.id()
        );
        
        match event.event_type() {
            "redis.command.get" => {
                println!("  -> Executing GET command");
                // 模拟处理时间
                thread::sleep(Duration::from_millis(10));
                EventResult::Success
            }
            "redis.command.set" => {
                println!("  -> Executing SET command"); 
                thread::sleep(Duration::from_millis(15));
                EventResult::Success
            }
            "redis.command.del" => {
                println!("  -> Executing DEL command");
                thread::sleep(Duration::from_millis(8));
                EventResult::Success
            }
            _ => {
                println!("  -> Unknown command type");
                EventResult::Skipped
            }
        }
    }

    fn name(&self) -> &str {
        &self.name
    }

    fn can_handle(&self, event_type: &str) -> bool {
        event_type.starts_with("redis.command.")
    }
}

/// 示例：监控处理器
struct MonitoringHandler;

impl DynamicEventHandler for MonitoringHandler {
    fn handle_dynamic(&self, event: &redis_rs2::event::DynamicEvent) -> EventResult {
        println!(
            "[MONITOR] Event {} processed (age: {}ms)",
            event.id(),
            event.metadata.age_millis()
        );
        EventResult::Success
    }

    fn name(&self) -> &str {
        "MonitoringHandler"
    }

    fn can_handle(&self, _event_type: &str) -> bool {
        true // 处理所有事件
    }
}

fn main() {
    println!("🚀 Event-Driven System Demo");
    println!("==========================\n");

    // 创建分发器配置
    let config = DispatcherConfig {
        worker_count: 2,
        batch_size: 5,
        priority_queue: true,
        ..Default::default()
    };

    // 创建事件分发器
    let mut dispatcher = EventDispatcher::new(config);

    // 注册处理器
    let cmd_handler1 = Arc::new(RedisCommandHandler::new("Handler-1"));
    let cmd_handler2 = Arc::new(RedisCommandHandler::new("Handler-2"));
    let monitor_handler = Arc::new(MonitoringHandler);

    dispatcher.register_handler("redis.command.get", cmd_handler1.clone());
    dispatcher.register_handler("redis.command.set", cmd_handler2.clone());
    dispatcher.register_handler("redis.command.del", cmd_handler1.clone());
    dispatcher.register_handler("*", monitor_handler); // 通配符处理器

    // 启动分发器
    println!("Starting event dispatcher...");
    dispatcher.start();

    // 创建并发布事件
    println!("Publishing events...\n");

    // 发布一些普通优先级的事件
    for i in 0..3 {
        let event = Event::new(
            "redis.command.get",
            Box::new(StringPayload(format!("GET key_{}", i))) as Box<dyn redis_rs2::event::EventPayload>
        );
        dispatcher.publish(event).unwrap();
    }

    // 发布一个高优先级事件
    let high_priority_event = Event::with_metadata(
        EventMetadata::new("redis.command.set")
            .with_priority(Priority::High)
            .with_source("client_001")
            .with_correlation_id("txn_12345"),
        Box::new(StringPayload("SET important_key value".to_string())) as Box<dyn redis_rs2::event::EventPayload>
    );
    dispatcher.publish(high_priority_event).unwrap();

    // 发布更多事件
    for i in 0..2 {
        let event = Event::new(
            "redis.command.del",
            Box::new(StringPayload(format!("DEL old_key_{}", i))) as Box<dyn redis_rs2::event::EventPayload>
        );
        dispatcher.publish(event).unwrap();
    }

    // 等待事件处理完成
    println!("Waiting for events to be processed...\n");
    thread::sleep(Duration::from_millis(500));

    // 显示统计信息
    let stats = dispatcher.get_stats();
    println!("📊 Dispatcher Statistics:");
    println!("  Total Events: {}", stats.total_events);
    println!("  Processed Events: {}", stats.processed_events);
    println!("  Processing Rate: {:.2} events/sec", stats.processing_rate);
    println!("  Success Rate: {:.1}%", stats.success_rate * 100.0);
    println!("  Uptime: {}s\n", stats.uptime_seconds);

    // 显示处理器统计
    let handler_stats = dispatcher.get_handler_stats();
    println!("📈 Handler Statistics:");
    for stat in handler_stats {
        println!("  {}: {} processed, {:.1}% success rate, {:.1}ms avg time",
            stat.name,
            stat.processed_count,
            stat.success_rate() * 100.0,
            stat.avg_processing_time()
        );
    }

    // 停止分发器
    println!("\nStopping dispatcher...");
    dispatcher.stop();
    
    println!("✅ Demo completed!");
}